import React, { useMemo, useEffect, useState } from 'react';
import { createForm } from '@formily/core';
import { markRaw } from '@formily/reactive';
import { observer } from '@formily/react';
import { Form as FormilyForm } from '@formily/antd';

import { createBehavior, createResource } from '@inbiz/core';
import { usePrefix, DnFC, getMessage, useTreeNode } from '@inbiz/react';
import { getSiteType, useApp } from '@inbiz/utils';
import { InbizContext } from '@inbiz/render';

import { AllSchemas } from '../../common/schemas';
import { Form as FormLocale } from './locale';

import './styles.less';

const inbiz = function () { };
inbiz.appInfo = {} as object;
inbiz.userInfo = {} as object;
inbiz.browser = {
  designer: true,
};
markRaw(inbiz);

export const Form: DnFC<React.ComponentProps<typeof FormilyForm>> = observer(
  (props) => {
    const prefix = usePrefix('designable-form');
    const appInfo = useApp();
    const [extendsObj, $extendsObj] = useState({ isExtend: false, height: 0 });
    const node = useTreeNode();
    const form = useMemo(
      () =>
        createForm({
          designable: true,
        }),
      [],
    );
    const inbizContext = useMemo(() => {
      inbiz.appInfo = appInfo;
      inbiz.userInfo = appInfo.userInfo;
      return inbiz;
    }, [appInfo]);

    useEffect(() => {
      const designContentHeight = document.querySelector('.dn-pc-simulator')?.clientHeight || 0;
      const isContent = node.operation.workspace.id == 'content';
      const isExtendsHeight = node.children.some((item) => item?.props?.['x-decorator-props']?.['style']?.height == '100%')

      $extendsObj({
        isExtend: isExtendsHeight && isContent,
        height: designContentHeight
      })
    }, [node.children.length])

    return (
      !props['x-display'] && (
        <InbizContext.Provider value={inbizContext as any}>
          <FormilyForm
            {...props}
            style={{ ...props.style, height: extendsObj.isExtend ? extendsObj?.height : '100%' }}
            className={prefix}
            form={form}
          >
            {props.children}
          </FormilyForm>
        </InbizContext.Provider>
      )
    );
  },
);
Form.Behavior = createBehavior({
  name: 'Form',
  selector: (node) => node.componentName === 'Form',
  designerProps(node) {
    return {
      draggable: !node.isRoot,
      cloneable: !node.isRoot,
      deletable: !node.isRoot,
      droppable: false,
      allowAppend: (target, sources) => {
        if (target.operation.workspace.id != 'content') {
          if (
            sources &&
            sources[0] &&
            sources[0].props['x-component'] == 'ModalDesign'
          ) {
            return false;
          }
        }
        return true;
      },
      propsSchema: {
        type: 'object',
        properties: {
          form: {
            type: 'void',
            'x-component': 'FormTab',
            properties: {
              attribute: {
                type: 'void',
                'x-component': 'FormTab.TabPane',
                'x-component-props': {
                  tab: getMessage('global.attribute'),
                },
                properties: AllSchemas.FormLayout.properties as any,
              },
              style: {
                type: 'void',
                'x-component': 'FormTab.TabPane',
                'x-component-props': {
                  tab: getMessage('global.style'),
                },
                properties: {
                  style: {
                    type: 'void',
                    properties: {
                      'style.background': {
                        'x-component': 'BackgroundStyleSetter',
                      },
                      'style.boxShadow': {
                        'x-component': 'BoxShadowStyleSetter',
                      },
                      'style.font': {
                        'x-component': 'FontStyleSetter',
                      },
                      'style.padding': {
                        'x-component': 'BoxStyleSetter',
                      },
                      'style.borderRadius': {
                        'x-component': 'BorderRadiusStyleSetter',
                      },
                      'style.border': {
                        'x-component': 'BorderStyleSetter',
                      },
                      'style.opacity': {
                        'x-decorator': 'FormItem',
                        'x-component': 'Slider',
                        'x-component-props': {
                          defaultValue: 1,
                          min: 0,
                          max: 1,
                          step: 0.01,
                        },
                      },
                    },
                  },
                },
              },
              senior: {
                type: 'void',
                'x-component': 'FormTab.TabPane',
                'x-component-props': {
                  tab: getMessage('global.senior'),
                },
                properties: {
                  model: {
                    type: 'object',
                    'x-decorator': 'FormItem',
                    'x-component': 'ChooseModuleEngine',
                  },
                },
              },
            },
          },
        },
      },
      defaultProps: {
        labelCol: 6,
        wrapperCol: getSiteType() == '1' ? 18 : 12,
        layout: getSiteType() == '1' ? 'vertical' : 'horizontal',
        labelAlign: getSiteType() == '1' ? 'left' : 'right',
      },
    };
  },
  designerLocales: FormLocale,
});

Form.Resource = createResource({
  title: {
    'zh-CN': '表单',
    'en-US': 'Form',
  },
  icon: 'FormLayoutSource',
  elements: [
    {
      componentName: 'Field',
      props: {
        type: 'object',
        'x-component': 'Form',
        'x-component-props': {
          style: {
            background: 'rgba(255,255,255,1)',
          },
        },
      },
    },
  ],
});
